<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Filter, CaretTop, CaretBottom, Search, Picture } from '@element-plus/icons-vue';
import CustomerLayout from '@/components/customer/CustomerLayout.vue';
import { storeApi, categoryApi } from '@/api/customer';
import type { Store, Category } from '@/types/customer';
import { StoreSearchSort } from '@/types/customer';

const router = useRouter();
const route = useRoute();

// 搜索参数
const searchParams = reactive({
  keyword: '',
  category: '',
  sortBy: 'rating', // 默认按评分排序
  sortOrder: 'desc' as 'asc' | 'desc',
  page: 1,
  pageSize: 10
});

// 搜索结果
const stores = ref<Store[]>([]);
const categories = ref<Category[]>([]);
const total = ref(0);
const loading = ref(false);

// 筛选条件
const filters = reactive({
  minRating: 0,
  maxDeliveryTime: 0,
  minPrice: 0,
  maxPrice: 100
});

// 是否显示筛选器
const showFilter = ref(false);

// 映射排序字段到API字段
const mapSortField = (sortBy: string): StoreSearchSort => {
  const sortFieldMap: Record<string, StoreSearchSort> = {
    'rating': StoreSearchSort.RATING,
    'monthlySales': StoreSearchSort.SALES, 
    'distance': StoreSearchSort.DISTANCE,
    'price': StoreSearchSort.PRICE
  };
  return sortFieldMap[sortBy] || StoreSearchSort.RATING;
};

// 处理店铺数据，添加默认值
const processStoreData = (store: any) => ({
  ...store,
  monthSales: store.monthlySales || store.monthSales || 0,
  distance: store.distance || 0,
  deliveryTime: store.averageDeliveryTime || store.deliveryTime || 30,
  minOrder: store.minOrderAmount || store.minOrder || 0,
  deliveryFee: store.deliveryFee || 0,
  rating: store.rating || 0,
  tags: store.tags || [],
  coverImage: store.logo || store.coverImage // 映射logo到coverImage
});

// 初始化搜索参数
const initSearchParams = () => {
  const { keyword, category, sortBy, sortOrder, page } = route.query;
  
  if (keyword) searchParams.keyword = keyword as string;
  if (category) searchParams.category = category as string;
  if (sortBy) searchParams.sortBy = sortBy as string;
  if (sortOrder) searchParams.sortOrder = (sortOrder as 'asc' | 'desc');
  if (page) searchParams.page = parseInt(page as string);
};

// 搜索商家
const searchStores = async () => {
  try {
    loading.value = true;
    
    // 构造搜索参数，包含筛选条件
    const params = {
      keyword: searchParams.keyword,
      categoryId: searchParams.category ? parseInt(searchParams.category) : undefined,
      sortBy: mapSortField(searchParams.sortBy),
      sortOrder: searchParams.sortOrder,
      page: searchParams.page,
      size: searchParams.pageSize,
      // 添加筛选条件
      minRating: filters.minRating > 0 ? filters.minRating : undefined,
      maxDeliveryTime: filters.maxDeliveryTime > 0 ? filters.maxDeliveryTime : undefined,
      minPrice: filters.minPrice > 0 ? filters.minPrice : undefined,
      maxPrice: filters.maxPrice < 100 ? filters.maxPrice : undefined
    };
    
    const res = await storeApi.getStores(params);
    if (res && res.data && res.data.data) {
      const responseData = res.data.data;
      // 处理分页响应数据
      if (responseData.content && Array.isArray(responseData.content)) {
        // 分页对象格式
        stores.value = responseData.content.map(processStoreData);
        total.value = responseData.totalElements || responseData.content.length;
      } else if (Array.isArray(responseData)) {
        // 简单数组格式
        stores.value = responseData.map(processStoreData);
        total.value = responseData.length;
      } else {
        console.warn('未知的响应格式:', res.data);
        stores.value = [];
        total.value = 0;
      }
    }
  } catch (error) {
    console.error('搜索商家失败:', error);
    ElMessage.error('搜索商家失败');
    stores.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await categoryApi.getCategories();
    categories.value = res.data || [];
  } catch (error) {
    console.error('获取分类失败:', error);
  }
};

// 切换排序方式
const handleSortChange = (sort: string) => {
  if (searchParams.sortBy === sort) {
    // 如果点击的是当前排序字段，则切换排序顺序
    searchParams.sortOrder = searchParams.sortOrder === 'asc' ? 'desc' : 'asc';
  } else {
    // 如果点击的是新的排序字段，则设置为降序
    searchParams.sortBy = sort;
    searchParams.sortOrder = 'desc';
  }
  searchParams.page = 1;
  search();
};

// 分页变化
const handlePageChange = (page: number) => {
  searchParams.page = page;
  search();
  // 滚动到页面顶部
  window.scrollTo({ top: 0, behavior: 'smooth' });
};

// 清除筛选条件（保留原有的简单清除功能）
const clearFilters = () => {
  searchParams.category = '';
  searchParams.sortBy = 'rating';
  searchParams.sortOrder = 'desc';
  searchParams.page = 1;
  // 只有在有关键词时才搜索
  if (searchParams.keyword.trim()) {
    search();
  }
  showFilter.value = false;
};

// 执行搜索
const search = () => {
  // 验证搜索条件：需要关键词或分类
  if (!searchParams.keyword.trim() && !searchParams.category) {
    ElMessage.warning('请输入搜索关键词或选择分类');
    return;
  }
  
  // 重置分页到第一页
  searchParams.page = 1;
  
  // 只搜索商家
  searchStores();
  
  // 更新URL参数
  router.push({
    path: '/customer/search',
    query: searchParams
  });
};

// 跳转到商家详情页
const goToStore = (storeId: number) => {
  router.push(`/customer/store/${storeId}`);
};

// 选择分类
const selectCategory = (categoryId: string) => {
  searchParams.category = categoryId;
  searchParams.page = 1;
  search();
};

// 格式化评分提示
const formatRating = (val: number) => {
  return `${val}星以上`;
};

// 应用筛选
const applyFilters = () => {
  searchParams.page = 1;
  search();
  showFilter.value = false;
};

// 清除所有筛选条件
const clearAllFilters = () => {
  filters.minRating = 0;
  filters.maxDeliveryTime = 0;
  filters.minPrice = 0;
  filters.maxPrice = 100;
  searchParams.category = '';
  searchParams.sortBy = 'rating';
  searchParams.sortOrder = 'desc';
  searchParams.page = 1;
  // 只有在有关键词时才搜索
  if (searchParams.keyword.trim()) {
    search();
  }
  showFilter.value = false;
};

// 监听路由变化
watch(
  () => route.query,
  () => {
    initSearchParams();
    // 只有在有搜索条件时才执行搜索
    if (searchParams.keyword.trim() || searchParams.category) {
      search();
    }
  },
  { immediate: false } // 不立即执行，避免重复搜索
);

onMounted(() => {
  initSearchParams();
  fetchCategories();
  
  // 只有在有搜索关键词或分类时才自动搜索
  if (searchParams.keyword.trim() || searchParams.category) {
    search();
  }
});
</script>

<template>
  <CustomerLayout>
    <div class="search-page">
      <div class="search-header">
        <h1 class="search-title">
          <span v-if="searchParams.keyword">搜索"{{ searchParams.keyword }}"的结果</span>
          <span v-else-if="searchParams.category">分类搜索结果</span>
          <span v-else>全部结果</span>
        </h1>
        
        <!-- 搜索输入框 -->
        <div class="search-input-wrapper">
          <el-input
            v-model="searchParams.keyword"
            placeholder="搜索商家"
            class="search-input"
            clearable
            @keyup.enter="search"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="search">搜索</el-button>
        </div>
        
        <div class="search-filter-btn" @click="showFilter = !showFilter">
          <el-button link>
            <el-icon><Filter /></el-icon>
            筛选
          </el-button>
        </div>
      </div>
      
      <!-- 分类筛选 -->
      <div class="category-filter" v-if="categories.length > 0">
        <el-scrollbar>
          <div class="category-list">
            <div 
              class="category-item" 
              :class="{ active: !searchParams.category }"
              @click="selectCategory('')"
            >
              全部
            </div>
            <div 
              v-for="category in categories" 
              :key="category.id"
              class="category-item"
              :class="{ active: searchParams.category === category.id.toString() }"
              @click="selectCategory(category.id.toString())"
            >
              {{ category.name }}
            </div>
          </div>
        </el-scrollbar>
      </div>
      
      <!-- 筛选区域 -->
      <div class="search-filter" v-show="showFilter">
        <div class="filter-section">
          <h3>高级筛选</h3>
          
          <!-- 评分筛选 -->
          <div class="filter-item">
            <label>最低评分</label>
            <el-slider 
              v-model="filters.minRating" 
              :min="0" 
              :max="5" 
              :step="0.5"
              show-stops
              :format-tooltip="formatRating"
            />
          </div>
          
          <!-- 配送时间筛选 -->
          <div class="filter-item">
            <label>最长配送时间</label>
            <el-radio-group v-model="filters.maxDeliveryTime">
              <el-radio :value="0">不限</el-radio>
              <el-radio :value="15">15分钟内</el-radio>
              <el-radio :value="30">30分钟内</el-radio>
              <el-radio :value="45">45分钟内</el-radio>
              <el-radio :value="60">60分钟内</el-radio>
            </el-radio-group>
          </div>
          
          <!-- 起送价格筛选 -->
          <div class="filter-item">
            <label>起送价格范围</label>
            <div class="price-range">
              <el-input-number 
                v-model="filters.minPrice" 
                :min="0" 
                :max="100" 
                size="small"
                placeholder="最低"
              />
              <span>-</span>
              <el-input-number 
                v-model="filters.maxPrice" 
                :min="0" 
                :max="200" 
                size="small"
                placeholder="最高"
              />
            </div>
          </div>
        </div>
        
        <div class="filter-actions">
          <el-button @click="clearAllFilters">重置</el-button>
          <el-button type="primary" @click="applyFilters">应用筛选</el-button>
        </div>
      </div>
      
      <!-- 排序选项 -->
      <div class="sort-options">
        <div 
          class="sort-item" 
          :class="{ active: searchParams.sortBy === 'rating' }"
          @click="handleSortChange('rating')"
        >
          评分
          <el-icon class="sort-icon" v-if="searchParams.sortBy === 'rating'">
            <CaretTop v-if="searchParams.sortOrder === 'asc'" />
            <CaretBottom v-else />
          </el-icon>
        </div>
        
        <div 
          class="sort-item" 
          :class="{ active: searchParams.sortBy === 'monthlySales' }"
          @click="handleSortChange('monthlySales')"
        >
          销量
          <el-icon class="sort-icon" v-if="searchParams.sortBy === 'monthlySales'">
            <CaretTop v-if="searchParams.sortOrder === 'asc'" />
            <CaretBottom v-else />
          </el-icon>
        </div>
        
        <div 
          class="sort-item" 
          :class="{ active: searchParams.sortBy === 'distance' }"
          @click="handleSortChange('distance')"
        >
          距离
          <el-icon class="sort-icon" v-if="searchParams.sortBy === 'distance'">
            <CaretTop v-if="searchParams.sortOrder === 'asc'" />
            <CaretBottom v-else />
          </el-icon>
        </div>
      </div>
      
      <!-- 搜索结果 -->
      <div class="search-results">
        <el-empty 
          description="未找到相关结果" 
          v-show="!loading && stores.length === 0"
        />
        
        <el-skeleton :rows="3" animated v-show="loading" :count="3" />
        
        <!-- 商家搜索结果 -->
        <div class="stores-result" v-show="!loading && stores.length > 0">
          <div 
            v-for="store in stores" 
            :key="`store-${store.id}`" 
            class="store-card"
            @click="goToStore(store.id)"
          >
            <div class="store-image">
              <el-image 
                :src="store.coverImage" 
                :alt="store.name"
                fit="cover"
                loading="lazy"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="store-info">
              <h3 class="store-name">{{ store.name }}</h3>
              <div class="store-rating">
                <el-rate 
                  v-model="store.rating" 
                  disabled 
                  text-color="#FF9900"
                  show-score 
                  score-template="{value}" 
                />
                <span class="monthly-sales">月售 {{ store.monthSales }}+</span>
              </div>
              <div class="store-tags">
                <el-tag 
                  v-for="(tag, index) in store.tags" 
                  :key="`store-${store.id}-tag-${index}`" 
                  size="small" 
                  effect="plain"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <div class="store-delivery">
                <span>{{ store.deliveryTime }}分钟</span>
                <span>{{ store.distance }}km</span>
                <span>起送¥{{ store.minOrder }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination" v-show="total > searchParams.pageSize">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.page"
          @current-change="handlePageChange"
        />
      </div>
    </div>
  </CustomerLayout>
</template>

<style scoped>
.search-page {
  padding: 20px 0;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.search-title {
  font-size: 24px;
  color: #8b4513;
  margin: 0;
  flex: 1;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  flex: 2;
  max-width: 500px;
  gap: 10px;
}

.search-input {
  width: 100%;
}

.search-filter-btn {
  display: flex;
}

/* 分类筛选样式 */
.category-filter {
  margin-bottom: 15px;
}

.category-list {
  display: flex;
  gap: 10px;
  padding: 5px 0;
}

.category-item {
  padding: 6px 12px;
  border-radius: 16px;
  background-color: #f5f5f5;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
}

.category-item.active {
  background-color: #ff9800;
  color: white;
}

.search-filter {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.filter-item {
  margin-bottom: 20px;
}

.filter-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.price-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.price-range .el-input-number {
  width: 100px;
}

.price-range span {
  color: #666;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-section h3 {
  font-size: 16px;
  color: #8b4513;
  margin-bottom: 10px;
}

.category-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.sort-options {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #f5f5f5;
  padding-bottom: 10px;
}

.sort-item {
  padding: 8px 16px;
  cursor: pointer;
  color: #666;
  display: flex;
  align-items: center;
}

.sort-item.active {
  color: #ff9800;
  font-weight: bold;
}

.sort-icon {
  margin-left: 4px;
}

/* 商家列表样式 */
.stores-result {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.store-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.3s;
}

.store-card:hover {
  transform: translateY(-5px);
}

.store-image {
  height: 140px;
  overflow: hidden;
}

.store-image .el-image {
  width: 100%;
  height: 100%;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.store-info {
  padding: 15px;
}

.store-name {
  font-size: 18px;
  margin: 0 0 10px;
  color: #8b4513;
}

.store-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.monthly-sales {
  margin-left: 10px;
  font-size: 12px;
  color: #999;
}

.store-tags {
  margin-bottom: 10px;
}

.store-delivery {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stores-result {
    grid-template-columns: 1fr;
  }
  
  .sort-options {
    overflow-x: auto;
  }
  
  .search-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-input-wrapper {
    max-width: 100%;
    width: 100%;
  }
}
</style>
